<template>
	<view class="newOrder">
		<view class="form">
			<view class="form_item">

				<!-- {{ $store.state.devices }} -->
				<view class="text"><text>*</text>客户:</view>
				<view class="input1">
					<input v-model="user" placeholder="请选择用户" type="text" />
					<view @tap="open" class="btn1"> 选择 </view>
				</view>
			</view>
			<view class="form_item">
				<view class="text"> 订单日期 :</view>
				<view class="input">
					<view class="date">
						<!-- <picker
              mode="date"
              :value="time"
              @change="(e) => bindDateChange(e, 'beginTime')"
            > -->
						<view class="select-input">
							<view @tap="showDate = true" class="select-input-left">
								<text v-if="time">{{ time }}</text>
								<text v-else>{{ timeText }}</text>
							</view>
							<u-icon v-if="closeFlag" @tap="close" name="close" color="#272727" size="24rpx"></u-icon>
							<u-icon v-else @tap="showDate = true" name="arrow-right" color="#272727" size="24rpx">
							</u-icon>
						</view>
						<!-- </picker> -->
					</view>
				</view>
			</view>
			<view class="from_footer">
				<view class="form_item2">
					<view class="text"> 出货量: </view>
					<view class="input"> {{ ShipmenNum }} </view>
				</view>
				<view class="form_item2">
					<view class="text"> 出货金额:</view>
					<view class="input"> {{ ShipmenPrice | unifyNumber }} </view>
				</view>
				<view class="form_item2">
					<view class="text"> 退货量:</view>
					<view class="input"> {{ returnNum | unifyNumber }} </view>
				</view>
				<view class="form_item2">
					<view class="text"> 退货金额: </view>
					<view class="input"> {{ returnPrice | unifyNumber }} </view>
				</view>
				<view class="form_item2">
					<view class="text2"> 总金额:</view>
					<view class="input"> {{ totalPrice | unifyNumber }} </view>
				</view>
			</view>

			<view class="btn">
				<button @tap="MergeData">合并数据</button>
				<button @tap="ExpandData">展开数据</button>

				<!-- <button @tap="accounts">更新单价</button> -->

				<!-- <button @tap="accounts">核算数据1</button> -->

				<button @tap="Registration">挂单</button>
			</view>
			<image v-show="signUrl" @tap="imgListPreview(signUrl)" style="width: 250rpx;
							          height: 250rpx;
							           background-color: transparent;
							          padding: 10rpx;
							          margin-top: 20rpx;
							          border-radius: 10rpx;
							        " :src="signUrl" mode="aspectFit" alt="" />
			<canvas canvas-id="signCanvas" canvas-type="2d" id="signCanvas"
				:style="'border:0px solid; width:200x; height:170px;'"></canvas>

			<!-- <canvas canvas-id="signCanvas" class="canvas"
									:style="'border:0px solid; width:200' + 'px; height:200px'"></canvas> -->
		</view>
		<view class="article">
			<view class="title">
				<view class="text">出货清单</view>
				<view class="btn">
					<button @tap="addNewOeder(0) ">
						添加
					</button>
					<!-- <button @tap="skip('/pages/newOrder/scanCode?type=0')">扫码</button> -->
				</view>
			</view>

			<view class="article_table">
				<myTable :proType="0" :data="ShipmentList" />
			</view>
		</view>
		<view class="article last">
			<view class="title">
				<view class="text">退货清单</view>
				<view class="btn">
					<button @tap="addNewOeder(1)">
						添加
					</button>
					<!-- <button @tap="skip(`/pages/newOrder/scanCode?type=1`)">扫码</button> -->
				</view>
			</view>
			<view class="article_table">
				<myTable :proType="1" :data="returnList" />
			</view>
		</view>
		<view class="footer_btn">
			<button @tap="skip(`/pages/newOrder/htz_signature`)">签名</button>
			<button @tap="submitOut">提交并打印</button>
			<button @tap="submit">提交</button>
		</view>
		<CustomerScreening ref="child" @saveUser="saveUser" />
		<u-calendar :show="show1" mode="single" @confirm="confirm"></u-calendar>
		<myDatePick @bindDateChange="bindDateChange" ref="myDatePick" :show.sync="showDate" />
		<billCanvas :user="user" :time="time" :signUrl="signUrl" ref="billCanvas" />
	</view>
</template>

<script>
	import CustomerScreening from "../../components/CustomerScreening.vue";
	import myTable from "../../components/table.vue";
	import myDatePick from "../../components/myDatePick.vue";
	import ReplceInfo from "../../utils/repleceInfo.js"
	import billCanvas from "../../components/billCanvas.vue";
	import {
		cal
	} from '@/utils/cal.js';
	import {
		mapState
	} from 'vuex'

	var app = getApp();
	export default {
		data() {
			const _this = this
			return {
				resBaseUrl: _this.resBaseUrl,
				showDate: false,
				// 步进器
				value: 1000,
				// 客户
				user: "",
				// 日历

				show1: false,
				// 日历
				time: "",
				// 默认当前时间
				timeText: "默认当前时间",
				// 签名url
				signUrl: "",
				// 数据展示
				dataShow: true,
				billUrl: "",
				// 客户cid
				cid: "",
				// 是否是当前时间
				closeFlag: false,
				proSkus1: [],
				proSkus2: [],
				type: "",
				orderIdSale: "",
				imageData: null,
				imageSrc: "/static/\images/long.png",
				drawW: 200,
				drawH: 200,

			};
		},
		components: {
			CustomerScreening,
			myTable,
			myDatePick,
			billCanvas
		},
		computed: {
			...mapState(["ShipmentList", "returnList"]),
			// 出货量
			ShipmenNum() {
				var num = 0;
				if (this.$store.state.ShipmentListCopy) {
					this.$store.state.ShipmentListCopy.forEach((item) => {
						num += +item.orderNum;
					});
					return num;

				}
			},
			// 出货金额
			ShipmenPrice() {
				if (this.$store.state.ShipmentListCopy.length > 0) {
					var total = this.$store.state.ShipmentListCopy.reduce((pre, cur) => {
						return pre + cal.cheng(cur.orderNum, cur.realPrice).toNumber();
					}, 0);
					return total;
				} else {
					return "0";
				}
			},
			// 退货量
			returnNum() {
				var num = 0;
				if (this.$store.state.returnListCopy) {
					this.$store.state.returnListCopy.forEach((item) => {
						num = cal.jia(num, item.orderNum).toNumber();
					});
					return num;
				}
			},
			// 退货金额
			returnPrice() {
				if (this.$store.state.returnListCopy.length > 0) {
					var total = this.$store.state.returnListCopy.reduce((pre, cur) => {
						return pre + cal.cheng(cur.orderNum, cur.realPrice).toNumber();
					}, 0);
					return total;
				} else {
					return "0";
				}
			},
			// 总金额
			totalPrice() {
				return cal.jian(this.ShipmenPrice, this.returnPrice).toNumber();
			},
		},
		onShow() {},
		methods: {
			addNewOeder(type) {
				if (!this.user) {
					uni.showToast({
						title: "请选择客户",
						icon: "none"
					})
					return
				}
				this.skip(
					`/pages/newOrder/add?proType=${type}&cid=${this.cid}&cname=${this.user}&orderDay=${this.time || uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')}`
					)
			},
			imgListPreview(img) {
				console.log(img, "img");
				var urlList = []
				urlList.push(img) //push中的参数为 :src="item.img_url" 中的图片地址
				uni.previewImage({
					indicator: "none",
					loop: true,
					urls: urlList,
					longPressActions: true
				})
			},
			// 核算
			accounts() {
				this.proSkus1 = []
				this.proSkus2 = []
				this.saveProIds()
				if (this.proSkus1.length > 0) {
					this.$api.qryProductInfoApi({
						cid: this.cid,
						proSkus: this.proSkus1
					}).then(res => {
						let data = []
						this.$store.state.ShipmentList.forEach(item => {
							let index = res.result.list.find(item2 => item2.proId == item.proId) || {}
							index.proPrice = index.proPrice || item.realPrice
							data.push({
								...item,
								realPrice: index.proPrice
							})
						})
						this.$store.commit("accounts1", data)
					})
				}
				if (this.proSkus2.length > 0) {
					this.$api.qryProductInfoApi({
						cid: this.cid,
						proSkus: this.proSkus2
					}).then(res => {
						let data = []
						this.$store.state.returnList.forEach(item => {
							let index = res.result.list.find(item2 => item2.proId == item.proId) || {}
							index.proPrice = index.proPrice || item.realPrice

							data.push({
								...item,
								realPrice: index.proPrice
							})
						})
						this.$store.commit("accounts2", data)
						// this.$store.commit("accounts2", res.result.list.map((item, index) => {
						// 	return {
						// 		...this.$store.state.returnList[index],
						// 		realPrice: item.proPrice
						// 	}
						// }))
					})
				}
			},
			// 存proIds的方法
			saveProIds() {
				if (this.$store.state.ShipmentList.length > 0) {
					this.$store.state.ShipmentList.forEach(item => {
						if (item.proSku) {
							this.proSkus1.push(item.proSku)
						}
					})
				}
				if (this.$store.state.returnList.length > 0) {
					this.$store.state.returnList.forEach(item => {
						if (item.proSku) {
							this.proSkus2.push(item.proSku)
						}
					})
				}
			},
			close() {
				this.time = ''
				this.closeFlag = false
				// this.showDate = true
				// this.bindDateChange()
				// this.time=formateIOS(new Date())
				// this.time=uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM')
			},
			bindDateChange(e, key) {
				console.log(e)
				this.closeFlag = true
				this.time = e
			},
			// 打开客户筛选
			open() {
				this.$refs.child.open();
			},
			saveUser(data) {
				this.user = data.cname;
				this.cid = data.cid;
				this.accounts()
				this.$refs.child.close();
			},
			// 日历
			confirm(e) {
				this.show1 = false;
				this.time = e[0];
			},
			// 合并数据
			MergeData() {
				this.$store.commit("MergeData");
			},
			// 展开数据
			ExpandData() {
				this.$store.commit("ExpandData");
			},
			// 提交
			async submit() {
				// let billUrl = await this.$refs.billCanvas.draw()
				// return
				if (this.user) {
					let list = [
						...this.$store.state.ShipmentList,
						...this.$store.state.returnList,
					]
					// if (list.length == 0) {
					// 	uni.showToast({
					// 		title: "产品不能为空",
					// 		icon: "none"
					// 	})
					// }
					if (this.time == "") {
						this.time = uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')
					}
					console.log(123);
					let billUrl = await this.$refs.billCanvas.draw()

					this.$api
						.orderCreateApi({
							orderIdSale: this.orderIdSale,
							cname: this.user,
							cid: this.cid,
							details: [
								...this.$store.state.ShipmentList,
								...this.$store.state.returnList,
							],
							orderDay: this.time,
							orderUrl: billUrl,
							signUrl: this.signUrl,
						})
						.then((res) => {
							if (res.code == 200) {
								// console.log(res.result.list)
								uni.showToast({
									title: "提交成功",
									icon: "none",
								});
								let list = [...this.$store.state.ShipmentList,
									...this.$store.state.returnList,
								]
								let newData = list.find(element => !element.proSku)
								this.$store.commit("clear");
								// if(!this.type){

								let pages = getCurrentPages();
								let beforePage = pages[pages.length - 2];
								console.log(beforePage.route == "pages/index/index");
								if (beforePage.route == "pages/index/index") {
									uni.redirectTo({
										url: "/pages/order/index"
									})
								} else if (this.type == 1) {
									uni.navigateBack({
										delta: 2
									})
								} else {
									uni.navigateBack()
								}
								// }else{
								// 	uni.redirectTo({
								// 		url:"pages/order/index"
								// 	})
								// }

							}
						});
				} else {
					uni.showToast({
						title: "请输入用户",
						icon: "none"
					})
				}
			},
			// 挂单
			Registration() {
				if (this.user) {
					if (!this.time) {
						this.time = uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')
					}
					this.$api
						.createSaveApi({
							cname: this.user,
							details: [
								...this.$store.state.ShipmentList,
								...this.$store.state.returnList,
							],
							orderDay: this.time,
							signUrl: this.signUrl,
						})
						.then((res) => {
							if (res.code == 200) {
								this.$store.commit("clear");
								uni.showToast({
									title: "提交成功",
									icon: "none",
								});
								uni.redirectTo({
									url: "/pages/order/index",
								});
							}
						});
				} else {
					uni.showToast({
						title: '请输入用户',
						icon: "none"
					})


				}
			},
			saveOrder() {
				var that = this;
				that.$api
					.orderCreateApi({
						orderIdSale: that.orderIdSale,
						cname: that.user,
						details: [
							...that.$store.state.ShipmentList,
							...that.$store.state.returnList,
						],
						orderDay: that.time,
						signUrl: that.signUrl,
						orderUrl: that.billUrl,
					})
					.then((res) => {
						if (res.code == 200) {
							uni.showToast({
								title: "提交成功，正在打印",
								icon: "none",
							});

							var userInfo = app.globalData.userInfo;
							let totalPrice = 0;
							let P1 = that.$store.state.ShipmentList.reduce((pre, cur) => {
								return pre + Number(cur.realPrice) * Number(cur.orderNum);
							}, 0)
							let P2 = that.$store.state.returnList.reduce((pre, cur) => {
								return pre + Number(cur.realPrice) * Number(cur.orderNum);
							}, 0)
							totalPrice = P1 - P2;
							// console.log(P1, P2)
							var jpPrinterObj = ReplceInfo.jpPrinterObj.createNew();
							jpPrinterObj.printData({
								title: userInfo.mchCompany + " - 销售单",
								cname: that.user,
								orderTime: that.time,
								totalPrice: totalPrice,
								ShipmentList: that.$store.state.ShipmentList,
								returnList: that.$store.state.returnList,
								imageData: that.imageData,
							})
							uni.redirectTo({
								url: "/pages/order/index"
							})
							// let list = [...that.$store.state.ShipmentList,
							// ...that.$store.state.returnList,
							// ]
							// let newData = list.find(element => !element.proSku)
						}
					});

			},
			async submitOut() {
				// console.log(app.globalData.BLEInformation.deviceId,1)
        let contentFlag = uni.getStorageSync('contentFlag')
        if (contentFlag == 1) {
          uni.showModal({
            content: '当前默认打印参数为标签打印，是否前往设置？',
            success: function(res) {
              if (res.confirm) {
                // console.log('用户点击确定');
                uni.navigateTo({
                  url: "/pages/setup/Bluetooth"
                })
              } else if (res.cancel) {
                console.log('用户点击取消');
              }
            }
          });
          return
        }
				var that = this;
				if (this.user) {
					let list = [
						...this.$store.state.ShipmentList,
						...this.$store.state.returnList,
					]
					if (list.length == 0) {
						uni.showToast({
							title: "产品不能为空",
							icon: "none"
						})
						return
					}
          var deviceId = uni.getStorageSync('deviceId');
          if (deviceId == "") {
						uni.navigateTo({
							url: "/pages/setup/Bluetooth",
						});
						return
					}
					if (this.time == "") {
						this.time = uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss')
					}


					that.billUrl = await this.$refs.billCanvas.draw()
					if (that.signUrl == "") {
						that.saveOrder();
					} else {
						uni.canvasGetImageData({
							canvasId: 'signCanvas',
							x: 0,
							y: 0,
							width: 200,
							height: 100,
							success: function(res) {
								console.log("获取画布数据成功" + res);
								that.imageData = res;
								that.saveOrder();
							},
							complete: function(res) {
								console.log("finish");
							},
							fail: function(res) {

								uni.showToast({
									title: '获取画布数据失败',
									icon: 'none'
								});
							}
						}, that);

					}
				} else {
					uni.showToast({
						title: "请输入或选择用户",
						icon: "none"
					})
				}

			},
		},
		onUnload() {
			this.$store.commit("clear");
		},
		onLoad(option) {
			this.type = option.type
			this.orderIdSale = option.orderIdSale
			this.$store.state.returnList = []
			this.$store.state.ShipmentListCopy = []
			this.$store.state.returnListCopy = []
			this.$store.state.ShipmentList = []
			uni.$on("tempFilePath", (data) => {
				// console.log(data)
				this.base64 = data.data
			});
			uni.$on("emitParams", (data) => {
				console.log('data.url' + data.url);
				this.signUrl = data.url;
				var that = this; //"https://web.mjerp123.com/sign/2c24e11689474e998e4ea4aca4379899.jpg",
				uni.getImageInfo({
					src: data.url,
					success: (res) => {
						console.log("res=" + res.path);
						const ctx = uni.createCanvasContext('signCanvas', that);
						// ctx.beginPath();
						ctx.fillStyle = "#fff"; // 默认白色
						ctx.fillRect(0, 0, 200, 100) // fillRect(x,y,宽度，高度)
						//  ctx.setStrokeStyle();
						// ctx.fillRect(0, 0, 375, 170);
						ctx.drawImage(data.res, 0, 0, 200, 100);
						ctx.draw();

					}
				})

			});
			if (option.orderIdSale && option.type == 0) {
				this.$api
					.orderDetailApi({
						data: {
							orderIdSale: option.orderIdSale,
						},
					})
					.then((res) => {
						this.user = res.result.orderSale.cname;
						this.cid = res.result.orderSale.cid;
						// this.time = res.result.orderSale.orderDay;
						this.$store.commit("copyOrder", {
							ShipmentList: res.result.sellList,
							returnList: res.result.returnList,
						});
					});
			} else if (option.orderIdSale && option.type == 1) {
				this.$api
					.orderSaleTempListApi({
						data: {
							orderIdSale: option.orderIdSale,
						},
					})
					.then((res) => {
						this.user = res.result.orderSale.cname;
						this.cid = res.result.orderSale.cid;
						this.time = '';
						this.$store.commit("copyOrder", {
							ShipmentList: res.result.sellList,
							returnList: res.result.returnList,
						});
					});
			}

			this.$nextTick(() => {
				this.open()
			})
		},
		created() {
			this.$nextTick(() => {
				// this.$refs.myDatePick.confirm()
				// console.log()
				// this.time = uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:ss')


			})
		}
	};
</script>

<style lang="scss" scoped>
	page {
		background: #f1f1f1;
		height: 100vh;
	}

	.newOrder {
		background-color: #f1f1f1;

		.form {
			padding: 38rpx 68rpx 32rpx 68rpx;
			background-color: #fff;

			// display: grid;
			// grid-template-columns:repeat(2,1fr);1
			// grid-template-rows:repeat(2,1fr);
			// margin-top: 38rpx;
			.form_item {
				color: #bdbdbd;
				margin-bottom: 36rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.text {
					width: 30%;
					text-align: right;
					margin-right: 10rpx;

					text {
						color: #fe3430;
					}
				}

				.input {
					text-align: center;
					flex: 1;

					input {
						height: 64rpx;
						background: #f2f2f2;
						border-radius: 47rpx;
						text-align: left;
						text-indent: 1em;
						flex: 1;
					}
				}

				.input1 {
					text-align: center;
					flex: 1;
					display: flex;
					align-items: center;

					input {
						height: 64rpx;
						background: #f2f2f2;
						border-radius: 47rpx;
						text-align: left;
						text-indent: 1em;
						flex: 1;
						color: #000;
					}

					.btn1 {
						height: 61rpx;
						width: 145rpx;
						line-height: 61rpx;
						background: #fe3430;
						border-radius: 31rpx;
						color: #fff;
						margin-left: 36rpx;
						text-align: center;
					}
				}
			}

			.btn {
				display: flex;
				justify-content: space-between;

				button {
					height: 58rpx;
					line-height: 58rpx;
					background: #fe3430;
					border-radius: 49rpx;
					color: #fff;
					padding: 0 20rpx;
					// margin-left: 0;
					// margin-right: 10rpx;
				}
			}
		}

		.article {
			padding: 32rpx 17rpx;

			.title {
				margin-bottom: 18rpx;
				// font-size: 1.125rem;
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-weight: 600;

				// .text {
				// 	background-color: #cfc;
				// 	width: 600rpx;
				// }

				.btn {
					// margin-left: 266rpx;
					display: flex;

					button {
						height: 61rpx;
						width: 145rpx;
						line-height: 61rpx;
						background: #fe3430;
						border-radius: 31rpx;
						color: #fff;
						margin-left: 36rpx;
					}
				}
			}

			.article_table {
				background: #ffffff;
				// height: 274rpx;
				border-radius: 20rpx;
				padding: 12rpx;
				box-sizing: border-box;
				color: #272727;
				position: relative;

				.title {

					height: 100rpx;
					display: flex;
					justify-content: space-around;
					align-items: center;
					border-bottom: 1px solid #f1f1f1;
				}

				.table_body {
					// background-color: #FE3430;

					.item {
						display: flex;
						justify-content: space-around;
					}
				}
			}
		}

		.last {
			margin-bottom: 180rpx;
		}

		.footer_btn {
			display: flex;
			position: fixed;
			bottom: 0rpx;
			margin-left: 50%;
			transform: translateX(-50%);
			background: #f1f1f1;
			width: 100%;
			padding: 30rpx 0;
			z-index: 999;

			button {
				background: url("/static/images/user/button.png");
				background-size: 220rpx 124rpx;
				width: 220rpx;
				height: 124rpx;
				line-height: 96rpx;
				color: #ffffff;
			}
		}
	}

	.date {
		width: 100%;

		.select-input {
			display: flex;
			align-items: center;
			justify-content: space-around;
			height: 64rpx;
			background: #f2f2f2;
			border-radius: 47rpx;
			text-align: left;
			text-indent: 1em;
			flex: 1;
			color: #000;
		}

		picker {
			flex: 1;
		}
	}

	.from_footer {
		padding: 38rpx 30rpx 32rpx 30rpx;
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		grid-template-rows: repeat(2, 1fr);
		text-align: right;

		.form_item2 {
			color: #bdbdbd;
			margin-bottom: 36rpx;
			display: flex;
			align-items: right;
			line-height: 40rpx;
			height: 40rpx;

			.text2 {
				// width: 200rpx;
				text-indent: 1em;
				font-size: 32rpx;
			}



		}
	}
</style>
